<?php
/**
 * @description
 *  用户管理等库函数
 *
 * filename : /admin/modules/admin/admin.libs.php
 * date     : 2009-1-23 14:59
 * author   : hotgun
 * email    : hotgun@163.com
 * 
 * (c)copyright hotgun
 *
 * $Id: /admin/modules/admin/admin.libs.php,v 1.0 2009-1-23 14:59 $
 */



/**
 * @description
 * 用户列表
 * 构造用户列表视图所需的变量
 * @author
 *  hotgun@163.com
 *
 * @param
 *  $page_size 分页大小
 * @return
 *  (array)用户列表视图所需变量
 */
function & li($page_size = ADM_PAGESIZE) {
    global $_TABLES;

    $view_var   = array();
    $tbl_main   = $_TABLES['admin'];
    $conn       = & get_db_conn();



    if(@(int)$_SESSION[$G_admin_session_key]['site_id'] > 0) { // 分站
		$where = "WHERE 1 AND site_id = '{$_SESSION[$G_admin_session_key]['site_id']}' ";
	} else {
		$where      = 'WHERE 1 ';
	}
    
    $username   = trim(@$_GET['username']);
    $valid      = @(int)$_GET['valid'];

    if($username != '') {
        $where .= "AND username LIKE '%$username%' ";
    }
    if($valid == 2) {
        $where .= "AND valid = '0' ";
    } elseif($valid == 1) {
        $where .= "AND valid = '1' ";
    }
    

	$site_id      = @(int)$_GET['site_id'];
	if($site_id	== '-1') {
		$where .= "AND site_id = 0 ";
	} elseif($site_id > 0) {
		$where .= "AND site_id = $site_id ";
	}
	


    // 分页处理开始
    $csql   = "SELECT COUNT(*) AS rs_count FROM $tbl_main $where";
    $rs     = $conn->GetRow($csql);


    $record_total   = @(int)$rs['rs_count'];
    $page_total     = ceil($record_total/$page_size);

    $page   = @(int)$_GET['page'];
    if($page > $page_total) $page = $page_total;
    if($page < 1) $page = 1;

    $view_var['record_total']   = $record_total;
    $view_var['page_total']     = $page_total;
    $view_var['page']           = $page;
    $view_var['page_size']      = $page_size;
    // 分页处理完毕


    // 列表处理开始
    $order_by   = trim(@$_GET['orderby']);
    $order_desc = @(int)$_GET['desc'];

    $str_order_by   = '';
    if($order_by != '') {
        $order_desc = ($order_desc!=1)?'ASC':'DESC';
        $str_order_by = "`{$order_by}` {$order_desc}, ";
    }

    $sql    = "SELECT * FROM $tbl_main
            $where 
            ORDER BY  $str_order_by uid DESC ";
    $rs = $conn->PageExecute($sql,$page_size,$page);
    $view_var['record'] = $rs->GetRows();

    return $view_var;
}

/**
 * @description
 * 用户详细信息读取
 * @author
 *  hotgun@163.com
 *
 * @param
 *  $id 用户ID
 * @return
 *  (array)用户详细信息视图所需变量 的引用
 */
function & read($id = 0) {
    global $_TABLES, $timestamp;

    $view_var   = array();
    $tbl_admin  = $_TABLES['admin'];
    if($id > 0) {
        $conn       = & get_db_conn();
        $sql        = "SELECT * FROM $tbl_admin WHERE uid = $id";
        $view_var   = $conn->GetRow($sql);
        $roles      = roleread($id);

        $view_var['relrs']  = $roles['relrs'];
        $view_var['rrs']    = $roles['rrs'];
    } else {
        $roles      = roleread(0);
        $view_var   = array(
            'uid'   => 0,
            'username'  => '',
            'realname'  => '',
            'password'  => '',
            'valid' => 1,
            'canrepass' => 1,
            'createtime'=> $timestamp,
            'lastip'    => '255.255.255.255',
            'lasttime'  => 0,
            'description'   => '',

            'relrs' => $roles['relrs'],
            'rrs'   => $roles['rrs'],
            );
    }
    return $view_var;
}

/**
 * @description
 * 读取用户角色信息
 * @author
 *  hotgun@163.com
 *
 * @param
 *  $id 用户ID
 * @return
 *  (array)用户角色和某用户拥有的角色
 */
function & roleread($uid) {
    global $_TABLES;
    $tbl_main   = $_TABLES['admin_roles'];
    $tbl_ass1   = $_TABLES['admin_roles_rel'];

    $conn   = & get_db_conn();
    $relrs  = array();
    if($uid > 0) {
        $sql    = "SELECT * FROM $tbl_ass1 WHERE uid = '$uid' ";
        $rs     = &$conn->Execute($sql);
        $relrs  = $rs->GetRows();
    }

    $sql    = "SELECT * FROM $tbl_main WHERE 1 ";
    $rs     = &$conn->Execute($sql);
    $rrs    = (!$rs->EOF) ? $rs->GetRows() : array();

    $roles  = array('relrs'=>&$relrs,'rrs'=>&$rrs);
    return $roles;
}

/**
 * @description
 * 读取文章分类并读取某用户对哪些分类有权限
 * @author
 *  hotgun@163.com
 * 
 * @param
 *  $id 用户ID
 * @return
 *  (array)用户角色和某用户拥有的角色
 */
function & cclassread($uid) {
    global $_TABLES, $class_var;
    $tbl_main   = $_TABLES['admin_cclass'];
    $tbl_ass1   = $_TABLES['admin'];
    $view_var   = array();

    $conn   = & get_db_conn();

    $sql    = "SELECT * FROM $tbl_main WHERE uid = '$uid' ";
    $rs     = &$conn->Execute($sql);
    $rs     = (!$rs->EOF) ? $rs->GetRows() : array();


    // 分析$rs里的内容， 用继承的关系，分析所有id下的子分类，得到所有能管理的分类的集合
    $str    = '';
    foreach($rs as $v) {
        // $v['cid'];
        $str    .= $v['cid'] . ',';
    }
    $arr    = explode(',', $str);



    $sql    = "SELECT * FROM $tbl_ass1 WHERE uid = $uid ";
    $view_var=$conn->GetRow($sql);
    $view_var['rightcid']   = array_unique($arr);



    // $arr 中装了的就是当前有权限的分类
    return $view_var;
}


/**
 * @description
 * 保存栏目权限信息
 * @author
 *  hotgun@163.com
 *
 * @param
 *  $id 用户ID
 * @return
 *  (boolean)true|false
 */
function cclass() {
    global $_TABLES;
    $tbl_main   = $_TABLES['admin_cclass'];


    $data   = $_POST['cclass'];
    // 判断uid的合法性
    $uid    = $data['uid'];


    // 得到当前用户的 $oldcid
    $conn   = & get_db_conn();
    $sql    = "SELECT * FROM $tbl_main WHERE uid = '$uid' ";
    $rs     = & $conn->Execute($sql);
    $oldcid = !$rs->EOF ? $rs->GetRows() : array();


    // 从POST中得到分类id
    $newccid    = $data['cid'];
    if(!is_array($newccid)) $newccid = array();


    // 找新关系里有，老关系没有的，增加
    $isql   = '';
    $dsql   = '';
    foreach($newccid as $newid) {
        $newid  = @(int)$newid;
        $find   = false;
        foreach($oldcid as $v) {
            if($newid == $v['cid']) {
                $find   = true;
                break;
            }
        }

        if(!$find) {
            $isql  .= "('$uid', '$newid'),";
        }
    }

    if($isql != '') {
        // 增加不在的
        $isql   = substr($isql, 0, strlen($isql)-1);
        $isql   = "INSERT INTO $tbl_main (uid, cid) VALUES $isql";
        $conn->Execute($isql);
    }



    // 找老关系里有，但是新关系里没有的，删除
    foreach($oldcid as $v) {
        $find   = false;
        foreach($newccid as $newid) {
            if(@(int)$newid == @(int)$v['cid']) {
                $find   = true;
                break;
            }
        }
        if(!$find) {
            $dsql  .= $v['cid'] . ',';
        }
    }

    if($dsql != '') {
        $dsql   = substr($dsql, 0, strlen($dsql)-1);
        $dsql   = "DELETE FROM $tbl_main WHERE cid IN ($dsql) AND uid = '$uid' ";
        $conn->Execute($dsql);
    }
    return 1;
}

/**
 * @description
 * 分析管理员角色
 * @author
 *  hotgun@163.com
 *
 * @param
 *  $id 用户ID
 * @return
 *  (boolean)true|false
 */
function syn_admin_roles($uid, $rel) {
    global $_TABLES;
    $tbl_main   = $_TABLES['admin_roles_rel'];
    if(!is_array($rel)) $rel = array();


    $conn   = & get_db_conn();
    $sql    = "SELECT * FROM $tbl_main WHERE uid = '$uid' ";
    $rs     = & $conn->Execute($sql);
    $oldrel = $rs->GetRows();


    // 找新关系里有，老关系没有的，增加
    $isql   = '';
    $dsql   = '';
    foreach($rel as $newid) {
        $newid  = @(int)$newid;
        $find   = false;
        foreach($oldrel as $v) {
            if($newid == $v['rid']) {
                $find   = true;
                break;
            }
        }

        if(!$find) {
            $isql  .= "('$uid', '$newid'),";
        }
    }

    if($isql != '') {
        // 增加不在的
        $isql   = substr($isql, 0, strlen($isql)-1);
        $isql   = "INSERT INTO $tbl_main (uid, rid) VALUES $isql";
        $conn->Execute($isql);
    }

    // 找老关系里有，但是新关系里没有的，删除
    foreach($oldrel as $v) {
        $find   = false;
        foreach($rel as $newid) {
            if(@(int)$newid == @(int)$v['rid']) {
                $find   = true;
                break;
            }
        }

        if(!$find) {
            $dsql  .= $v['rid'] . ',';
        }
    }

    if($dsql != '') {
        $dsql   = substr($dsql, 0, strlen($dsql)-1);
        $dsql   = "DELETE FROM $tbl_main WHERE rid IN ($dsql) AND uid = '$uid' ";
        $conn->Execute($dsql);
    }
}






function request() {
    global $action;
    $data = $_POST['admin'];
    if(empty($data['rid']))$data['rid'] = array();

    // 处理 is_not_valid / can_repass 两个值反转
    $data['valid']  = @(int)$data['is_not_valid']==1 ? 0:1;
    $data['canrepass'] = @(int)$data['can_not_repass']==1 ? 0:1;
    $data['can_not_modify_pass'] = @(int)$data['can_not_modify_pass']==0 ? 0:1;
    if($data['qx']==1){
        $data['site_id']=0;
        $data['station_id']=0;
        $data['city']=0;
        $data['city1']=0;
    }elseif($data['qx']==2){
        $data['site_id']=0;
        $data['station_id']=0;
    }else{
        $data['city']=0;
        $data['city1']=0;
    }
    $rule   = array(
        'username'  => 'i_string|len:1:50|check_own:"^[a-z]+([A-Za-z0-9_\.]+)*$"', 
        'password'  => 'i_string|len:1:50',
        'realname'  => 'i_string|len:1:50',
        'usermemo'  => 'i_empty|i_string|len:0:5122',
        );
    if($action == 'u.modify') $rule['password']   = 'i_empty|i_string|len:1:30';


    $def_err= array(
        'username'  => '“登录用户名”必须填写，必须以字母开头后续字符为字母数组下划线和半角句点的组合，且长度必须在1～50个字符之间！', 
        'password'  => '“用户密码”必须填写，且长度必须在1～30个字符之间！', 
        'realname'  => '“真实姓名”必须填写，且长度必须在1～50个字符之间！',
        'usermemo'  => '“描述信息”长度不能超过512个字符！',
        );

    $result = data_validator($data, $rule, $def_err);
    if($result === true) {
        if($data['can_not_modify_pass'] == 0 && $data['confirmpass'] !=$data['password']) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                    "两次输入密码不一致！", 
                    __FILE__,
                    __LINE__);
        }
    } else {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        $v, 
                        __FILE__,
                        __LINE__);
        }
    }

    if($GLOBALS['ERR']->Count > 0) {
        return false;
    } else {
        return $data;
    }
}

function add() {
    global $_TABLES, $timestamp;
    $tbl_admin  = $_TABLES['admin'];

    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        // 先查看是否有同名用户
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_admin WHERE username = '{$result['username']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '系统中已经存在用户名为<FONT COLOR=\"red\">' . $result['username'] . '</FONT>的用户，无法当前添加操作！', 
                __FILE__,
                __LINE__);
        } else {
            $result['createtime']   = $timestamp;
            $result['password']     = md5($result['password']);
            $conn->AutoExecute($tbl_admin,$result,'INSERT');
            $uid    = $conn->Insert_ID();

            syn_admin_roles($uid, $result['rid']);
            return $uid;
        }
    }
    return false;
}

function modify() {
    global $_TABLES, $timestamp;
    $tbl_admin  = $_TABLES['admin'];

    $result = request();
    if($result !== false) {
        $conn   = & get_db_conn();

        // 先查看是否有同名用户
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_admin WHERE username = '{$result['username']}' AND uid <> '{$result['uid']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '系统中已经存在用户名为<FONT COLOR=\"red\">' . $result['username'] . '</FONT>的用户，无法完成当前修改操作！', 
                __FILE__,
                __LINE__);
        } else {
            if($result['can_not_modify_pass'] > 0) {
                unset($result['password']);
            } else {
                $result['password'] = md5($result['password']);
            }
            $conn->AutoExecute($tbl_admin,$result,'UPDATE','uid=' . $result['uid'] . '');

            syn_admin_roles($result['uid'], $result['rid']);
            return $result['uid'];
        }
    }
    return false;
}

function del() {
    global $_TABLES;
    $tbl_admin  = $_TABLES['admin'];

    $deltype    = @$_POST['deltype'];
    if($deltype == 'all') {
        // 删除POST传递过来的 item_id 
        // 批量删除
        $item_id= $_POST['item_id'];
        $str_in = '';
        if(is_array($item_id) && sizeof($item_id) > 0) {
            foreach($item_id as $v) {
                $v  = @(int)$v;
                $str_in .= ($str_in == '')?"{$v}":",{$v}";
            }
        } else {
            $item_id = @(int)$item_id;
            if($item_id > 0) $str_in = $item_id;
        }
    } else {
        // get传递过来的删除 单条删除
        $item_id= @(int)$_GET['item_id'];
        $str_in = $item_id;
    }

    if($str_in != '') {
        $conn   = & get_db_conn();
        $sql    = "DELETE FROM $tbl_admin WHERE uid IN ({$str_in}) ";
        if($conn->Execute($sql)) {
            // 删除用户成功后，需要删除用户对应的角色关系和文章内容关系



            js_success('删除指定用户成功！');
        }
    }
}

function self() {
    global $_TABLES, $timestamp;
    $tbl_admin  = $_TABLES['admin'];

    $data = $_POST['admin'];
    $rule['password']   = 'i_empty|i_string|len:1:30';
    $def_err['password']= '“用户密码”必须填写，且长度必须在1～30个字符之间！';

    $result = data_validator($data, $rule, $def_err);
    if($result === true) {
        if($data['confirmpass'] !=$data['password']) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                    "两次输入密码不一致！", 
                    __FILE__,
                    __LINE__);
        }
    } else {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        $v, 
                        __FILE__,
                        __LINE__);
        }
    }
    if($GLOBALS['ERR']->Count > 0) {
        return false;
    } else {
        global $G_admin_session_key;
        $result = $data;
        $result['uid'] = @(int)$_SESSION[$G_admin_session_key]['uid'];
    }


    $conn   = & get_db_conn();

    // 先查看原始密码是否一致
    $sql = "SELECT password FROM $tbl_admin WHERE uid = '{$result['uid']}' ";
    $rs = $conn->GetRow($sql);
    if(!$rs) {
        $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
            '当前用户不存在，无法完成当前修改操作！', 
            __FILE__,
            __LINE__);
    } else {
        if($rs['password'] == md5($result['oldpassword'])) {
            $result['password'] = md5($result['password']);
            $conn->AutoExecute($tbl_admin,$result,'UPDATE','uid=' . $result['uid'] . '');
            return $result['uid'];
        } else {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '旧密码输入错误！', 
                __FILE__,
                __LINE__);
        }
    }
    return false;
}


/**
 * @description
 * 附件列表
 */
function ali($page_size = ADM_PAGESIZE) {
    global $_TABLES;

    $view_var   = array();
    $tbl_attachments = $_TABLES['attachments'];
    $conn   = & get_db_conn();


    $where  = 'WHERE 1 ';
    $key    = trim(@$_GET['key']);
    if($key != '') {
        $where .= "AND (filename LIKE '%$key%' OR description LIKE '%$key%') ";
    }

    $inuse  = !array_key_exists('inuse', $_GET) ? -1 :  @(int)$_GET['inuse'];
    if($inuse == 1) {
        $where .= "AND item_id > 0 ";
    } elseif($inuse == 0) {
        $where .= "AND item_id = 0 ";
    }



    // 分页处理开始
    $csql   = "SELECT COUNT(*) AS rs_count FROM $tbl_attachments $where";
    $rs     = $conn->GetRow($csql);


    $record_total   = @(int)$rs['rs_count'];
    $page_total     = ceil($record_total/$page_size);

    $page   = @(int)$_GET['page'];
    if($page > $page_total) $page = $page_total;
    if($page < 1) $page = 1;

    $view_var['record_total']   = $record_total;
    $view_var['page_total']     = $page_total;
    $view_var['page']           = $page;
    $view_var['page_size']      = $page_size;
    // 分页处理完毕


    // 列表处理开始
    $order_by   = trim(@$_GET['orderby']);
    $order_desc = @(int)$_GET['desc'];

    $str_order_by   = '';
    if($order_by != '') {
        $order_desc = ($order_desc!=1)?'ASC':'DESC';
        $str_order_by = "`{$order_by}` {$order_desc}, ";
    }

    $sql    = "SELECT * FROM $tbl_attachments
            $where 
            ORDER BY  $str_order_by aid DESC ";

    $rs = $conn->PageExecute($sql,$page_size,$page);
    $view_var['record'] = $rs->GetRows();

    return $view_var;
}

/**
 * @description
 * 删除附件
 */
function adel() {
    global $_TABLES, $save_flag, $G_abs_upload;
    $tbl_attachments = $_TABLES['attachments'];


    $deltype    = @$_POST['deltype'];
    if($deltype == $save_flag) {
        // 删除POST传递过来的 item_id
        // 批量删除
        $item_id= $_POST['item_id'];
        $str_in = '';
        if(is_array($item_id) && sizeof($item_id) > 0) {
            foreach($item_id as $v) {
                $v  = @(int)$v;
                $str_in .= ($str_in == '')?"{$v}":",{$v}";
            }
        } else {
            $item_id = @(int)$item_id;
            if($item_id > 0) $str_in = $item_id;
        }
    } else {
        // get传递过来的删除 单条删除
        $item_id= @(int)$_GET['item_id'];
        $str_in = $item_id;
    }
    if($str_in != '') {
        $conn   = & get_db_conn();
        // 得到相关的附件信息，删除服务器上的文件后再删除数据库信息
        $sql    = "SELECT fileurl FROM $tbl_attachments WHERE aid IN ({$str_in}) ";
        $rs     = &$conn->Execute($sql);
        if(!$rs) {}
        else {
            while (!$rs->EOF) {
                $del_abs = realpath($G_abs_upload . '/' . $rs->fields['fileurl']);
                if($del_abs) unlink($del_abs);
                $rs->MoveNext();
            }
        }
        $sql    = "DELETE FROM $tbl_attachments WHERE aid IN ({$str_in}) ";
        if($conn->Execute($sql)) {
            js_success('删除指定附件成功！');
        }
    }
    exit();
}

function basicupdate() {
    global $G_abs_includes;
    $data = @$_POST['basic'];

    // 更新 corp_name， site_name， seo_title， seo_keywords， seo_description
    require($G_abs_includes . '/conf/info.conf.php');

    $str_info_inc_php   = <<<EOT
\$G_cfg['site_info']['cms_name'] = '{$G_cfg['site_info']['cms_name']}';
\$G_cfg['site_info']['cms_ver'] = '{$G_cfg['site_info']['cms_ver']}';
\$G_cfg['site_info']['cms_copyright'] = '{$G_cfg['site_info']['cms_copyright']}';
\$G_cfg['site_info']['cms_packtime'] = '{$G_cfg['site_info']['cms_packtime']}';
\$G_cfg['site_info']['cms_packprogramer'] = '{$G_cfg['site_info']['cms_packprogramer']}';
\$G_cfg['site_info']['bq'] = '{$data['bq']}';
\$G_cfg['site_info']['addr'] = '{$data['addr']}';
\$G_cfg['site_info']['phone'] = '{$data['phone']}';
\$G_cfg['site_info']['qq'] = '{$data['qq']}';
\$G_cfg['site_info']['qq1'] = '{$data['qq1']}';
\$G_cfg['site_info']['qq2'] = '{$data['qq2']}';
\$G_cfg['site_info']['qq3'] = '{$data['qq3']}';
\$G_cfg['site_info']['qq4'] = '{$data['qq4']}';

\$G_cfg['site_info']['corp_name'] = '{$data['corp_name']}';
\$G_cfg['site_info']['site_name'] = '{$data['site_name']}';

\$G_cfg['site_info']['sms_url'] = '{$data['sms_url']}';
\$G_cfg['site_info']['sms_username'] = '{$data['sms_username']}';
\$G_cfg['site_info']['sms_password'] = '{$data['sms_password']}';
\$G_cfg['site_info']['sms_sitename'] = '{$data['sms_sitename']}';

\$G_cfg['site_info']['seo_title'] = '{$data['seo_title']}';
\$G_cfg['site_info']['seo_keywords'] = '{$data['seo_keywords']}';
\$G_cfg['site_info']['seo_description'] = '{$data['seo_description']}';

EOT;
    $str_info_inc_php   = "<" . "?php\r\n$str_info_inc_php\r\n?" . ">";

    // 保存配置文件
    write_to_file($G_abs_includes . '/conf/info.conf.php', $str_info_inc_php);
    return 1;
}
?>